package com.redis.springbootredis;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.hash.Jackson2HashMapper;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Map;


/**
 * @author: 李德才
 * @description:
 * @create: 2021-02-21 21:00
 **/

@Component
public class TestRedis {

    RedisTemplate<String, String> redisTemplate;
    StringRedisTemplate stringRedisTemplate;
    ObjectMapper objectMapper;

    public TestRedis(@Qualifier("createRedisTemplate") RedisTemplate<String, String> redisTemplate, StringRedisTemplate stringRedisTemplate, ObjectMapper objectMapper) {
        this.redisTemplate = redisTemplate;
        this.stringRedisTemplate = stringRedisTemplate;
        this.objectMapper = objectMapper;
    }

    public void testRedis() {
//        高阶API
//        redisTemplate.opsForValue().set("k1", "啊啊啊");
//       // redis-cli 查看数据会发现数据乱码，需要使用 redis-cli  -p 6379 --raw
//        System.err.println(redisTemplate.opsForValue().get("k1"));
//        stringRedisTemplate.opsForValue().set("k2", "aaaa");
//        System.err.println(stringRedisTemplate.opsForValue().get("k2"));
//
////        低阶API
//        RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection();
//        redisConnection.set("k3".getBytes(), "测试".getBytes());
//        System.err.println(new String(redisConnection.get("k3".getBytes())));


//        hash
//        HashOperations<String, Object, Object> hashOperations = stringRedisTemplate.opsForHash();
//        hashOperations.put("jack", "age", "22");
//        hashOperations.put("jack", "sex", "1");
//        System.err.println(hashOperations.entries("jack"));


        /**
         * 需要自己处理成map
         **/
        Person person = new Person();
        person.setUserName("jack");
        person.setAge(26); //java.lang.Integer cannot be cast to java.lang.String
//        自定义序列化
//        stringRedisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        Jackson2HashMapper jackson2HashMapper = new Jackson2HashMapper(objectMapper,false); // false 当对象中的属性又是键值对的时候需要打开
        stringRedisTemplate.opsForHash().putAll("hash", jackson2HashMapper.toHash(person));
        Map<Object, Object> hash = stringRedisTemplate.opsForHash().entries("hash");
        Person redisPerson = objectMapper.convertValue(hash, Person.class);

        System.err.println(redisPerson.toString());


    }
}
